import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import { setToken, getToken, removeToken } from './utils/util'
import { getTokenFromUrl, getUrlParam } from './utils/urlParams'
import { isInIframe, getTokenFromParent, notifyReady, notifyTokenError } from './utils/iframeHelper'
import apiClient from './utils/axiosConfig'

Vue.config.productionTip = false
Vue.use(Element)

// 挂载工具方法到Vue原型
Vue.prototype.setToken = setToken
Vue.prototype.getToken = getToken
Vue.prototype.removeToken = removeToken
Vue.prototype.getUrlParam = getUrlParam
Vue.prototype.$apiClient = apiClient
Vue.prototype.baseUrl = "/api"

// 异步初始化token的函数
async function initializeToken() {
  let token = null
  
  // 1. 首先尝试从URL参数获取token
  token = getTokenFromUrl()
  if (token) {
    console.log('从URL参数获取到token:', token)
    setToken(token)
    return token
  }
  
  // 2. 如果在iframe中，尝试从父窗口获取token
  if (isInIframe()) {
    try {
      token = await getTokenFromParent()
      if (token) {
        console.log('从父窗口获取到token:', token)
        setToken(token)
        return token
      }
    } catch (error) {
      console.warn('从父窗口获取token失败:', error)
    }
  }
  
  // 3. 最后尝试从已存储的cookie获取token
  token = getToken()
  if (token) {
    console.log('从cookie获取到token:', token)
    return token
  }
  
  console.warn('未能获取到token')
  return null
}

// 创建Vue实例
const app = new Vue({
  router,
  render: h => h(App),
  async mounted() {
    try {
      const token = await initializeToken()
      
      // 如果在iframe中，通知父窗口应用状态
      if (isInIframe()) {
        if (token) {
          notifyReady({ hasToken: true, token })
        } else {
          notifyTokenError('未能获取到有效的token')
        }
      }
    } catch (error) {
      console.error('Token初始化失败:', error)
      if (isInIframe()) {
        notifyTokenError('Token初始化失败: ' + error.message)
      }
    }
  }
})

app.$mount('#app')
